package com.st.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.st.service.IDeptService;
import com.st.service.impl.DeptServiceImpl;

@WebServlet("/dept.do")
public class DeptServlet extends BaseServlet {

	private IDeptService deptService = new DeptServiceImpl();
	
	public void getAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 参数
		// 2. 业务
		List depts = deptService.getAll();
		
		// 3. 结果
		request.setAttribute("depts", depts);
		request.getRequestDispatcher("deptList.jsp").forward(request, response);
	}
	
	public void getAllJson(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1. 参数
		// 2. 业务
		List depts = deptService.getAll();
		// 3. 结果
		// 将查询到的depts里的部门信息, 变成一个JSON的字符串
		// did: 1, dname:开发部...., 使用第三方的jar包, 实现将对象直接转换为json格式的字符串
		// 常用的工具有GSON, Jackson
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String json = objectMapper.writeValueAsString(depts);
			
			response.getWriter().write(json);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
	}
	
	public void  search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 参数
		String key = request.getParameter("key");
		
		// 2. 业务
		List depts = deptService.search(key);
		// 3. 结果
		request.setAttribute("depts", depts);
		request.getRequestDispatcher("deptList.jsp").forward(request, response);
	}
	
	public void remove(HttpServletRequest request, HttpServletResponse response) {
		
	}
}
